package com.goldsprite.projecttemplategenerator.android;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import com.goldsprite.projecttemplategenerator.Platform;

import java.io.File;

public class AndroidApi implements Platform.IAndroidApi {
	private final Activity activity;
	private File pendingApkFile; // 保存需要安装的 APK 文件

	public AndroidApi(Activity activity) {
		this.activity = activity;
	}

	@Override
	public void installApk(File apkFile) {
		if (!apkFile.exists()) {
			Toast.makeText(activity, "安装文件不存在", Toast.LENGTH_SHORT).show();
			return;
		}

		this.pendingApkFile = apkFile; // 保存 APK 文件引用

		if (ApkInstaller.hasInstallPermission(activity)) {
			ApkInstaller.installApk(activity, apkFile);
		} else {
			ApkInstaller.requestInstallPermission(activity);
			new Handler(Looper.getMainLooper()).post(() -> {
				Toast.makeText(activity, "请允许安装未知来源应用后重试", Toast.LENGTH_SHORT).show();
			});
		}
	}

	public void retryPendingInstallation() {
		if (pendingApkFile != null && pendingApkFile.exists()) {
			ApkInstaller.installApk(activity, pendingApkFile);
		}
	}
}
